<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> 
    <title>Redis--COW（Copy On Write） - 天地维杰网</title>
    <meta name="keywords" content="系统架构,shutdown,不与天斗,Domino,博客,程序员,架构师,笔记,技术,分享,java,Redis">
    
    <meta property="og:title" content="Redis--COW（Copy On Write）">
    <meta property="og:site_name" content="天地维杰网">
    <meta property="og:image" content="/img/author.jpg"> 
    <meta name="title" content="Redis--COW（Copy On Write） - 天地维杰网" />
    <meta name="description" content="问题概述： 1、RDB的过程中是否会停止对外提供服务？ 2、RDB的过程中数据修改了，备份的是修改前的还是修改后的？ 3、RDB时是不是先把内容中的所有KV复制一份，保证数据不会被修改？" />
     
    <link rel="shortcut icon" href="http://www.shutdown.cn/img/favicon.ico" />
    <link rel="apple-touch-icon" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link rel="apple-touch-icon-precomposed" href="http://www.shutdown.cn/img/apple-touch-icon.png" />
    <link href="http://www.shutdown.cn/js/vendor/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/main.css" rel="stylesheet" type="text/css" />
    <link href="http://www.shutdown.cn/css/syntax.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
     fancybox: true, 
    motion: true
  };
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7826003325059020" crossorigin="anonymous"></script>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left page-home  ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-meta  custom-logo ">

  <div class="custom-logo-site-title">
    <a href="http://www.shutdown.cn"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">天地维杰网</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">人如秋鸿来有信，事若春梦了无痕</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
    <ul id="menu" class="menu">
      
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/redis/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-full"></i> <br />Redis
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/java/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-coffee"></i> <br />java
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/linux/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-linux"></i> <br />linux
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/daily/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bug"></i> <br />日常问题
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/spring/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-child"></i> <br />Spring和Springboot
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/mac/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-fire"></i> <br />Mac相关
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/middleware/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-gavel"></i> <br />中间件
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jiagou/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-rocket"></i> <br />架构
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/python/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-ship"></i> <br />python
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/front/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-bolt"></i> <br />前端
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/jvm/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-balance-scale"></i> <br />jvm
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/c/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-battery-empty"></i> <br />c语言
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/categories/web3/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-web3"></i> <br />web3
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/post/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档
          </a>
        </li>
      
        <li class="menu-item ">
          <a href="http://www.shutdown.cn/about/" rel="section">
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于
          </a>
        </li>
      
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger"> <i class="menu-item-icon fa fa-search fa-fw"></i> <br /> 搜索</a>
      </li>
    </ul>
    <div class="site-search">
      <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>

    </div>
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
<section id="posts" class="posts-expand">
  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">
      <h1 class="post-title" itemprop="name headline">
        <a class="post-title-link" href="http://www.shutdown.cn/post/redis-copy-on-write-detail/" itemprop="url">
        Redis--COW（Copy On Write）
        </a>
      </h1>
      <div class="post-meta">
      <span class="post-time">
<span class="post-meta-item-icon">
    <i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">时间：</span>
<time itemprop="dateCreated" datetime="2016-03-22T13:04:35+08:00" content="2023-02-10">
    2023-02-10
</time>
</span> 
      

  <span class="post-category" >
  &nbsp; | &nbsp;
  <span class="post-meta-item-icon">
    <i class="fa fa-folder-o"></i>
  </span>
  <span class="post-meta-item-text">分类：</span>
  
    <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
      <a href="http://www.shutdown.cn/categories/redis" itemprop="url" rel="index">
        <span itemprop="name">redis</span>
      </a>
      &nbsp; 
    </span>
  
</span>


      
 <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">转载</span>
</span>

       <span>
&nbsp; | &nbsp;
<span class="post-meta-item-icon">
    <i class="fa fa-eye"></i>
</span>
<span class="post-meta-item-text">阅读：</span>
<span class="leancloud-visitors-count">1532 字 ~4分钟</span>
</span>
      </div>
    </header>
    <div class="post-body" itemprop="articleBody">
    
    <div class="highlight"><pre style="background-color:#f8f8f8;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-fallback" data-lang="fallback"> 文章系转载，便于整理和分类，原文地址：https://zhuanlan.zhihu.com/p/339437815</code></pre></div>
    

    

<h2 id="摘要">摘要</h2>

<p>问题概述：
1、RDB的过程中是否会停止对外提供服务？
2、RDB的过程中数据修改了，备份的是修改前的还是修改后的？
3、RDB时是不是先把内容中的所有KV复制一份，保证数据不会被修改？</p>

<p>问题解决：使用<strong>Copy On Write</strong> <strong>写时复制</strong></p>

<h2 id="详细">详细</h2>

<p>在看Redis持久化方式中的RDB方式时，想到了几个问题：</p>

<p>1、 Redis是单线程的，那在RDB的过程中，是不是就没法对外提供服务了？
Redis操作快的一个重要原因是Redis的数据是在内存中存储和操作的，持久化本身是磁盘的IO操作，IO操作又是特别耗时的，RDB备份的过程对Redis来说是挺漫长的，如果Redis没法对外提供服务的话，对Redis的影响是很大的吧；
2、知道备份时不会阻塞对外服务，那在数据备份的过程中，有新的数据变更的操作发生时，备份的是变更前的数据还是变更后的数据呢？
另一个角度：RDB快照的是精确的<strong>一个时刻</strong>的内存数据呢？还是<strong>一段时间</strong>内的内存数据？
另一个角度：RDB快照是<strong>精确</strong>的还是<strong>模糊</strong>的？
3、既然是数据备份，在开始备份的时候，是不是要把Redis的所有数据现在内存中拷贝一份呢？那样的话平时Redis服务器的内存利用率就不能大于50%了啊？</p>

<h2 id="解答">解答</h2>

<p>1、RDB过程中会fork一个子进程，子进程做数据备份操作，主进程继续对外提供服务，所有Redis服务不会阻塞；
2、Copy On Write 机制，备份的是开始那个时刻内存中的数据；
3、Copy On Write 机制不需要把整个内存的数据都复制一份；</p>

<h2 id="copy-on-write-机制">Copy On Write 机制</h2>

<blockquote>
<p><strong>核心思路</strong>：fork一个子进程，只有在父进程发生写操作修改内存数据时，才会真正去分配内存空间，并复制内存数据，而且也只是复制被修改的内存页中的数据，并不是全部内存数据；</p>
</blockquote>

<ul>
<li>Redis中执行BGSAVE命令生成RDB文件时，本质就是调用Linux中的fork()命令，Linux下的fork()系统调用实现了copy-on-write写时复制；</li>
<li>fork()是类Unix操作系统上创建线程的主要方法，fork用于<strong>创建子进程</strong>（等同于当前进程的副本）；</li>
<li><strong>传统的</strong>普通进程复制，会直接将父进程的数据拷贝到子进程中，拷贝完成后，父进程和子进程之间的<strong>数据段</strong>和<strong>堆栈</strong>是相互独立的；</li>
<li>copy-on-write技术，在fork出子进程后，与父进程共享内存空间，两者只是虚拟空间不同，但是其对应的物理空间是同一个；</li>
</ul>

<h2 id="linux中copyonwrite实现原理">Linux中CopyOnWrite实现原理</h2>

<p>fork()之后，kernel把父进程中所有的内存页的权限都设为read-only，然后子进程的地址空间指向父进程。当父子进程都只读内存时，相安无事。当其中某个进程写内存时，CPU硬件检测到内存页是read-only的，于是触发页异常中断（page-fault），陷入kernel的一个中断例程。中断例程中，kernel就会把触发的异常的页复制一份，于是父子进程各自持有独立的一份。</p>

<p>CopyOnWrite的好处：
1、减少分配和复制资源时带来的瞬时延迟；
2、减少不必要的资源分配；
CopyOnWrite的缺点：
1、如果父子进程都需要进行大量的写操作，会产生大量的分页错误（页异常中断page-fault）;</p>

<h2 id="redis中的copyonwrite">Redis中的CopyOnWrite</h2>

<ul>
<li>Redis在持久化时，如果是采用BGSAVE命令或者BGREWRITEAOF的方式，那<strong>Redis会fork出一个子进程来读取数据，从而写到磁盘中</strong>。</li>
<li>总体来看，<strong>Redis还是读操作比较多</strong>。如果子进程存在期间，发生了大量的写操作，那可能就会出现很多的<strong>分页错误(页异常中断page-fault)</strong>，这样就得耗费不少性能在复制上。</li>
<li>而在<strong>rehash阶段上，写操作是无法避免</strong>的。所以Redis在fork出子进程之后，<strong>将负载因子阈值提高，尽量减少写操作</strong>，避免不必要的内存写入操作，最大限度地节约内存。</li>
</ul>

    </div>
    <footer class="post-footer">
     
 
<div class="post-tags">     
     
    <a href="http://www.shutdown.cn/tags/redis" rel="tag" title="redis">#redis#</a>
    
    <a href="http://www.shutdown.cn/tags/cow" rel="tag" title="COW">#COW#</a>
    
    <a href="http://www.shutdown.cn/tags/%e5%86%99%e6%97%b6%e5%a4%8d%e5%88%b6" rel="tag" title="写时复制">#写时复制#</a>
    
</div>



     <div class="post-nav">
    <div class="post-nav-next post-nav-item">
    
        <a href="http://www.shutdown.cn/post/deploy-contract-to-test-net-with-truffle/" rel="next" title="truffle 创建测试合约并部署到测试网络">
        <i class="fa fa-chevron-left"></i> truffle 创建测试合约并部署到测试网络
        </a>
    
    </div>

    <div class="post-nav-prev post-nav-item">
    
        <a href="http://www.shutdown.cn/post/face-exam-mysql-redis-consistency/" rel="prev" title="高频面试：如何保障 MySQL 和 Redis 的数据一致性？ ">
        高频面试：如何保障 MySQL 和 Redis 的数据一致性？  <i class="fa fa-chevron-right"></i>
        </a>
    
    </div>
</div>
      
     
     
     






    </footer>
  </article>
</section>

          </div>
        </div>
        <div class="sidebar-toggle">
  <div class="sidebar-toggle-line-wrap">
    <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
    <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
  </div>
</div>
<aside id="sidebar" class="sidebar">
  <div class="sidebar-inner">

  <ul class="sidebar-nav motion-element">
    <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
      文章目录
    </li>
    <li class="sidebar-nav-overview" data-target="site-overview">
      站点概览
    </li>
  </ul>

    <section class="site-overview sidebar-panel ">
      <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
        src="http://www.shutdown.cn/img/author.jpg"
        alt="不与天斗Domino" />
    <p class="site-author-name" itemprop="name">不与天斗Domino</p>
    <p class="site-description motion-element" itemprop="description"> 
        Programmer &amp; Architect</p>
</div>
      <nav class="site-state motion-element">
    <div class="site-state-item site-state-posts">
      <a href="http://www.shutdown.cn/post/">
        <span class="site-state-item-count">183</span>
        <span class="site-state-item-name">日志</span>
      </a>
    </div>
    <div class="site-state-item site-state-categories">    
        <a href="http://www.shutdown.cn/categories/">      
         
        <span class="site-state-item-count">15</span>
        
        <span class="site-state-item-name">分类</span>
        
        </a>
    </div>

    <div class="site-state-item site-state-tags">
        <a href="http://www.shutdown.cn/tags/">
         
        <span class="site-state-item-count">224</span>
        
        <span class="site-state-item-name">标签</span>
        </a>
    </div>
</nav>
      
      

      

      <div class="links-of-blogroll motion-element inline">
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=&amp;m=0&amp;s=220&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33&amp;bv=35" async="async"></script>
</div>

    </section>
    
<section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
    <div class="post-toc">
        <div class="post-toc-content"><nav id="TableOfContents">
<ul>
<li>
<ul>
<li><a href="#摘要">摘要</a></li>
<li><a href="#详细">详细</a></li>
<li><a href="#解答">解答</a></li>
<li><a href="#copy-on-write-机制">Copy On Write 机制</a></li>
<li><a href="#linux中copyonwrite实现原理">Linux中CopyOnWrite实现原理</a></li>
<li><a href="#redis中的copyonwrite">Redis中的CopyOnWrite</a></li>
</ul></li>
</ul>
</nav></div>
    </div>
</section>

  </div>
</aside>

      </div>
    </main>
   
    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  <span itemprop="copyrightYear">  &copy; 
  2013 - 2023</span>
  <span class="with-love"><i class="fa fa-heart"></i></span>
  <span class="author" itemprop="copyrightHolder">天地维杰网</span>
  <span class="icp" itemprop="copyrightHolder"><a href="https://beian.miit.gov.cn/" target="_blank">京ICP备13019191号-1</a></span>
</div>
<div class="powered-by">
  Powered by - <a class="theme-link" href="http://gohugo.io" target="_blank" title="hugo" >Hugo v0.63.2</a>
</div>
<div class="theme-info">
  Theme by - <a class="theme-link" href="https://github.com/xtfly/hugo-theme-next" target="_blank"> NexT
  </a>
</div>


      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
      <span id="scrollpercent"><span>0</span>%</span>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/fastclick/lib/fastclick.min.js?v=1.0.6"></script> 
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/vendor/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="http://www.shutdown.cn/js/vendor/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>

<script src="http://www.shutdown.cn/js/vendor/fancybox/jquery.fancybox.pack.js?v=2.1.5"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/utils.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/motion.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/affix.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/schemes/pisces.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/scrollspy.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/post-details.js"></script>
<script type="text/javascript" src="http://www.shutdown.cn/js/toc.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/bootstrap.js"></script>

<script type="text/javascript" src="http://www.shutdown.cn/js/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    jax: ["input/TeX", "output/HTML-CSS"],
    tex2jax: {
      inlineMath: [ ['$','$'] ],
      displayMath: [ ['$$','$$'] ],
      processEscapes: true
    },
    "HTML-CSS": { fonts: ["TeX"] }
  });
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML' async></script>
</body>
</html>